package simple.utils.processing;

import com.google.common.base.Preconditions;
import org.slf4j.Logger;

/**
 * Created with IntelliJ IDEA.
 * User: rehak
 * Date: 9/10/13
 * Time: 1:57 PM
 * To change this template use File | Settings | File Templates.
 */
public class PercentListeners {

    public enum LoggingLevel {
        ERROR, DEBUG, INFO, TRACE, WARN;
    }

    /**
     * Creates Percent listener which logs supplied message (replacing % symbol with _%, where underscore stands for percent completed)
     *
     * @param logger
     * @param level
     * @param s
     * @return
     */
    public static PercentListener loggingListener(final Logger logger, final LoggingLevel level, final String s) {
        return loggingListener(logger, level, s, 1);
    }

    /**
     * Creates Percent listener which logs supplied message (replacing % symbol with _%, where underscore stands for percent completed)
     *
     * @param logger
     * @param level
     * @param s
     * @return
     */
    public static PercentListener loggingListener(final Logger logger, final LoggingLevel level, final String s, final int modulo) {
        Preconditions.checkNotNull(level, "level must not be null");
        Preconditions.checkNotNull(logger);
        Preconditions.checkNotNull(s);
        Preconditions.checkArgument(modulo > -1);
        return new PercentListener() {
            @Override
            public void progressChanged(int percentComplete) {
                if (percentComplete % modulo == 0) {
                    String msg = s.replace("%", percentComplete + "%");
                    switch (level) {
                        case ERROR:
                            logger.error(msg);
                            break;
                        case DEBUG:
                            logger.debug(msg);
                            break;
                        case INFO:
                            logger.info(msg);
                            break;
                        case TRACE:
                            logger.trace(msg);
                            break;
                        case WARN:
                            logger.warn(msg);
                            break;
                        default:
                            throw new IllegalArgumentException("Unknown logging level " + level);
                    }
                }
            }
        };
    }
}
